<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-button type="primary" @click="showAddRolesList = true"
          >添加角色</el-button
        >
      </el-row>
      <el-row>
        <el-table :data="rolelist" border style="width: 100%" stripe>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <div class="expand_box">
                <el-row
                  v-for="(item1, index1) in scope.row.children"
                  :key="item1.id"
                  :class="['left_box', 'bgbottom', index1 === 0 ? 'bgtop' : '']"
                >
                  <el-col :span="5">
                    <el-tag
                      closable
                      @close="deleteRolesToRights(scope.row, item1.id)"
                      >{{ item1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <el-row
                      v-for="(item2, index2) in item1.children"
                      :key="item2.id"
                      :class="[index2 === 0 ? '' : 'bgtop', 'left_box']"
                    >
                      <el-col :span="6">
                        <el-tag
                          type="success"
                          closable
                          @close="deleteRolesToRights(scope.row, item2.id)"
                          >{{ item2.authName }}</el-tag
                        >
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <el-col :span="18">
                        <el-tag
                          type="warning"
                          v-for="item3 in item2.children"
                          :key="item3.id"
                          closable
                          @close="deleteRolesToRights(scope.row, item3.id)"
                          >{{ item3.authName }}
                        </el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </div>
              <!-- <pre>{{ scope.row }}</pre> -->
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="roleName" label="角色名称"> </el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
          <el-table-column label="操作" :width="300">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="getEditRoles(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteRoles(scope.row)"
                >删除</el-button
              >
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="getRightsTree(scope.row)"
                >分配权限</el-button
              >
              <!-- <pre>{{ scope.row }}</pre> -->
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 添加角色表单 -->
      <el-dialog
        title="添加角色"
        :visible.sync="showAddRolesList"
        @close="resetAddRoles"
        :close-on-click-modal="false"
      >
        <el-form
          :model="addRolesList"
          label-width="80px"
          ref="addRolesRef"
          :rules="addRolesRules"
          status-icon
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="addRolesList.roleName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input
              v-model="addRolesList.roleDesc"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="submitAddRoles">提交</el-button>
          <el-button type="primary" @click="resetAddRoles">重置</el-button>
        </div>
      </el-dialog>
      <!-- 修改角色表单 -->
      <el-dialog
        title="修改角色"
        :visible.sync="showEditRolesList"
        @close="resetEditRole"
        :close-on-click-modal="false"
      >
        <el-form
          :model="editRolesData"
          label-width="80px"
          ref="editRolesRef"
          :rules="editRolesRules"
          status-icon
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="editRolesData.roleName"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input
              v-model="editRolesData.roleDesc"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="subEditRoles(editRolesData.roleId)"
            >提交</el-button
          >
          <el-button @click="resetEditRole">重置</el-button>
        </div>
      </el-dialog>
      <!--分配权限 -->
      <el-dialog
        title="分配权限"
        :visible.sync="showRightsTree"
        @close="resetRights"
        :close-on-click-modal="false"
      >
        <el-tree
          :data="Rightlist"
          :props="rightProps"
          show-checkbox
          default-expand-all
          node-key="id"
          :default-checked-keys="defkeys"
          ref="rightListRef"
        ></el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetRights">重置</el-button>
          <el-button type="primary" @click="submitRights">确认</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      // 所有角色列表数据
      rolelist: [],
      showAddRolesList: false,
      addRolesList: {
        roleName: "",
        roleDesc: "",
      },
      addRolesRules: {
        roleName: [
          { required: "true", message: "请输入角色名称", trigger: "blur" },
          {
            min: 3,
            max: 6,
            message: "请输入长度为3至6个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: "true", message: "请输入角色描述", trigger: "blur" },
          {
            min: 6,
            max: 10,
            message: "请输入长度为6至10个字符",
            trigger: "blur",
          },
        ],
      },
      showEditRolesList: false,
      editRolesData: {},
      editRolesRules: {
        roleDesc: [
          { required: "true", message: "请输入角色描述", trigger: "blur" },
          {
            min: 6,
            max: 10,
            message: "请输入长度为6至10个字符",
            trigger: "blur",
          },
        ],
      },
      // 所有的权限
      Rightlist: [],
      rightProps: {
        label: "authName",
        children: "children",
      },
      showRightsTree: false,
      // 被选中的子级id的数组
      defkeys: [],
      // 树形控件中将要选中的角色id
      roleIds: "",
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    // 获取角色列表
    getRoleList() {
      axios
        .get("roles")
        .then(({ data: res }) => {
          this.rolelist = res.data;
          // console.log(res);
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "获取角色列表失败",
          });
        });
    },
    // 重置添加角色事件
    resetAddRoles() {
      this.$refs.addRolesRef.resetFields();
    },
    // 提交添加角色的事件
    submitAddRoles() {
      this.$refs.addRolesRef.validate((valid) => {
        if (!valid) return;
        axios
          .post("roles", this.addRolesList)
          .then(({ data: res }) => {
            // console.log(res);
            this.$message.success("添加角色成功");
            this.showAddRolesList = false;
            this.getRoleList();
          })
          .catch(() => {
            this.$message({
              type: "error",
              message: "获取角色列表失败",
            });
          });
      });
    },
    // 重置编辑角色
    resetEditRole() {
      this.$refs.editRolesRef.resetFields();
    },
    // 编辑角色事件，获取用户ID
    getEditRoles(rolesinfo) {
      axios
        .get(`roles/${rolesinfo.id}`)
        .then(({ data: res }) => {
          // this.roleIds = rolesinfo.id;
          console.log(this.roleIds);
          this.editRolesData = res.data;
          this.showEditRolesList = true;
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "获取用户ID失败",
          });
        });
    },
    // 提交编辑角色事件
    subEditRoles(id) {
      this.$refs.editRolesRef.validate((valid) => {
        if (!valid) return;
        axios
          .put(`roles/${id}`, this.editRolesData)
          .then(({ data: res }) => {
            // console.log(res);
            this.editRolesData = res.data;
            this.showEditRolesList = false;
            this.$message({
              type: "success",
              message: "修改成功",
            });
            this.getRoleList();
          })
          .catch(() => {
            this.$message({
              type: "error",
              message: "修改失败",
            });
          });
      });
    },
    // 删除角色事件
    deleteRoles(rolesinfo) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios
            .delete(`roles/${rolesinfo.id}`)
            .then(({ data: res }) => {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getRoleList();
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "删除失败",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除角色指定权限
    deleteRolesToRights(roleinfo, rightId) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios
            .delete(`roles/${roleinfo.id}/rights/${rightId}`)
            .then(({ data: res }) => {
              roleinfo.children = res.data;
              console.log(res);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            })
            .catch(() => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 展开分配权限
    getRightsTree(role) {
      axios
        .get(`rights/tree`)
        .then(({ data: res }) => {
          console.log(res);
          this.roleIds = role.id;
          this.Rightlist = res.data;
          this.getleafkeys(role, this.defkeys);
          this.showRightsTree = true;
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "获取权限失败",
          });
        });
    },
    // 递归有子组件的node，将其进行循环调用，直至没有子组件
    getleafkeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      } else {
        node.children.forEach((item) => {
          this.getleafkeys(item, arr);
        });
      }
    },
    // 监听分配权限对话框关闭
    resetRights() {
      this.defkeys = [];
    },

    // 分配权限提交
    submitRights() {
      // console.log(this.roleIds, 111111);
      // 将半选和全选的id保存在数组中
      const keys = [
        ...this.$refs.rightListRef.getCheckedKeys(),
        ...this.$refs.rightListRef.getHalfCheckedKeys(),
      ];
      const rid = keys.join(",");
      console.log(this.roleIds);
      axios
        .post(`roles/${this.roleIds}/rights`, { rids: rid })
        .then(({ data: res }) => {
          console.log(res);
          this.$message.success("更新权限成功");
          this.getRoleList();
          this.showRightsTree = false
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "更新权限失败",
          });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 7px;
}
.left_box {
  display: flex;
  align-items: center;
}
.bgbottom {
  border-bottom: 1px solid #eee;
}
.bgtop {
  border-top: 1px solid #eee;
}
.expand_box {
  padding: 20px 50px;
}
</style>